package com.chen.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

import javax.sql.DataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/14 23:18
 */
@Slf4j
@Configuration
public class Lang {

    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.getDefault());
        return localeResolver;
    }

    private static MessageSource messageSource;

    public Lang(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public static String get(String key) {
        String message = null;
        try {
            message = messageSource.getMessage(key, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            log.error(Utils.format("Get language error, key: [{}] , language: [{}] . error:    ", key, LocaleContextHolder.getLocale().toString()) + e);
        }
        if (StringUtils.isBlank(message)) {
            message = "Sorry, can't find the message!";
        }
        return message;
    }
}
